<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;

class CommonController extends Controller
{
    const OK                = 0;
    const OK_TXT    = '操作成功!';
    const EXP_PARAMS        = 1001;
    const EXP_PARAMS_TXT    = '参数有误!';
    const EXP_EMPTY         = 1002;
    const EXP_EMPTY_TXT     = '记录不存在!';
    const ERR_DB            = 2001;
    const ERR_DB_TXT        = 'DB异常!';
    const ERR_OPFAIL        = 2002;
    const ERR_OPFAIL_TXT    = '操作失败!';
    const ERR_AUTH_FAILED   = 2003;
    const ERR_AUTH_FAILED_TXT = '认证失败!';
    const EXP_USER            = 2004;
    const EXP_USER_TXT        = '用户不存在!';

    //初始后台认证
    public function init()
    {
        if ( \Yii::$app->user->isGuest) {
            return $this->goHome();
            exit;
        }
    }
    /**
     * 日期统一格式化
     * @param int $tm
     * @return string
     */
    public function dateformat( $tm )
    {
        return date( 'Y-m-d H:i', $tm );
    }


    /**
     * 通过URL获取结果
     * @param unknown $url
     * @param unknown $data
     * @param string  $method
     * @param unknown $timeout
     */
    public function getContent( $url, $params,  $timeout = 3 )
    {
        if( empty( $url ) )
        {
            return self::EXP_PARAMS;
        }
        $user_agent ='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
        $ch         = curl_init(); // 初始化CURL句柄
//         if( !empty( $proxy ) )
//         {
//             curl_setopt ( $ch, CURLOPT_PROXY, $proxy );//设置代理服务器
//         }
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt( $ch, CURLOPT_URL, $url ); //设置请求的URL
//         curl_setopt( $ch, CURLOPT_FAILONERROR, 1 ); // 启用时显示HTTP状态码，默认行为是忽略编号小于等于400的HTTP信息
//         curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );//启用时会将服务器服务器返回的“Location:”放在header中递归的返回给服务器
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );// 设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt( $ch, CURLOPT_POST, 1 );//启用POST提交
//         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE' );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $params ); //设置POST提交的字符串
//         curl_setopt($ch, CURLOPT_PORT, 80); //设置端口
        curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); // 超时时间
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
        curl_setopt( $ch, CURLOPT_USERAGENT, $user_agent );//HTTP请求User-Agent:头
//         curl_setopt( $ch, CURLOPT_HEADER, 1 );//设为TRUE在输出中包含头信息
//         $fp = fopen( 'example_homepage.txt', 'w' );//输出文件
//         curl_setopt( $ch, CURLOPT_FILE, $fp );//设置输出文件的位置，值是一个资源类型，默认为STDOUT (浏览器)。
        $http_header = array(
            'Accept-Language:   zh-cn',
            'Connection:        Keep-Alive',
            'Cache-Control:     no-cache'
            );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_header );//设置HTTP头信息
        $res       = curl_exec( $ch ); //执行预定义的CURL
        $info       = curl_getinfo( $ch ); //得到返回信息的特性
        $httpCode   = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
        $errorNo    = curl_errno( $ch );

        curl_close( $ch );
        return array(
            'data'      => $res,
           // 'info'      => $info,
            'errorNo'   => $errorNo,
            'errorMsg'  => '',
            'params'    => $params,
            'httpCode'  => $httpCode
            );
    }


    protected function strToHex($string)//字符串转十六进制
    {
        $hex="";
        for($i=0;$i<strlen($string);$i++)
            $hex.=dechex(ord($string[$i]));
        $hex=strtoupper($hex);
        return $hex;
    }

    protected function hexToStr($hex)//十六进制转字符串
    {
        $string="";
        for($i=0;$i<strlen($hex)-1;$i+=2)
            $string.=chr(hexdec($hex[$i].$hex[$i+1]));
        return  $string;
    }

    /**
        * 输出的数据结构
        * error_code 错误代码，0为没错误
        * msg错误信息
        * data用于扩展信息
        * render ajax或者页面返回
    */
    public function out($error_code=1, $msg = '', $data=array() ,$render='ajax'){
        $re = array(
            'state'=>$error_code,
            'msg'=>$msg,
            'data'=>$data,
            );
        if ($render=='ajax') {
            echo json_encode($re);
        }else{
            print_r($msg);exit;
            $this->render('//site/error',array('name'=>'出现错误','message'=>$msg));
        }
        exit;
    }

        /**
     *参数处理
     * name 参数的key
     * default 默认值，用于非必传
     * error_msg 如果该参数为必传，需要设置该错误提示
     */
        public function getParam($name, $default='', $error_msg='' ,$render='ajax'){
            $val = Yii::$app->getRequest()->getQueryParam($name, $default);
            if (empty($val)) {
                $val = Yii::$app->getRequest()->getBodyParam($name, $default);
            }
            if($val == '' && $error_msg != ''){
                $this->out(self::EXP_PARAMS, $error_msg,array(),$render);
            }
            return $val;
        }

     /**
         * 删除目录下的所有文件(不删除目录)
         */
     public static  function deldir($dir) {
            //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                        //self::deldir($fullpath);
                }
            }
        }

        closedir($dh);
    }

    /**
     * 数据导出excel(需加载phpexcel类)
     * @param string $dirName 文件夹路径
     * @param array $title 标题数组
     * @param array $data 二维数组
     * @param string $fileName 保存名称 不包括文件后缀
     * @author zhuge <zhuge@syswin.com>
     */
    public static   function dataExportExcel($dirName,$title,$data = array(),$fileName = ""){
        if(!file_exists($dirName)){
           mkdir($dirName, 0777, true);
       }
       if(empty($fileName)){
        $fileName = date('YmdHi').'.xls';
    }
    $outputFileName = $dirName.$fileName;
    $objectPHPExcel = new \PHPExcel();
    $objWriter = new \PHPExcel_Writer_Excel5($objectPHPExcel);
    $objProps = $objectPHPExcel->getProperties();
        $objProps->setCreator("syswin");  //创造者
        $objProps->setLastModifiedBy("syswin");   //最后修改时间
        $objectPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objectPHPExcel->getActiveSheet();
        //设置当前活动sheet(工作簿)的名称
        $objActSheet->setTitle('Sheet1');
        foreach ($title as $k => $v){
            $n = \PHPExcel_Cell::stringFromColumnIndex($k);
            $objActSheet->setCellValue($n.'1',$v);
            //设置单元格宽度
            $objActSheet->getColumnDimension($n)->setWidth(30);
            //设置单元格居中
            $objActSheet->getStyle($n)->applyFromArray(
                array(
                    'alignment' => array(
                     'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                     ),
                    )
                );
            //设置第一栏单元格加粗&居中
            $objActSheet->getStyle($n."1")->applyFromArray(
                array(
                    'font' => array (
                        'bold' => true
                        ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                        ),
                    )
                );
        }
        foreach ($data as $k => $v) {
            $line = $k + 2;
            foreach ($title as $key => $value){

                $n = \PHPExcel_Cell::stringFromColumnIndex($key);
                //$objActSheet->setCellValue($n.$line, array_shift($v));
                $objActSheet->setCellValueExplicit($n.$line, strval(array_shift($v)), \PHPExcel_Cell_DataType::TYPE_STRING);
                //$objActSheet->setCellValueExplicit('H'.($n+4) ,strval($product['identity_code']), PHPExcel_Cell_DataType::TYPE_STRING);

            }
        }
        $objWriter->save($outputFileName);
        return $fileName;
    }

}
